package com.motorola.accessories;

import java.lang.reflect.Method;

import android.content.Context;

public class MotWhisperAccessoryAdapter {

    // if we support FF, then we should be careful with the -1 value
    public static int CLASS_TYPE_INVALID = -1;
    public static int CLASS_TYPE_GENERIC_ACCESSORY = 0;
    public static int CLASS_TYPE_SIMPLE_DESK_DOCK = 1;
    public static int CLASS_TYPE_CAR_DOCK = 2;
    public static int CLASS_TYPE_HD_DOCK = 3;
    public static int CLASS_TYPE_LAP_DOCK = 4;
    public static int CLASS_TYPE_POWER_SUPPLY = 5;

    // returns an array of accessories enabled through whisper. each element represents
    // one whisper authenticated device
    // when an undock event occurs this should return a null array
    // apps should not store these values since these will change based on events coming in
    // each is a string of the form abcdefg,abcdf
    @SuppressWarnings("unchecked")
    public static String[] getWhisperAccessoryIds(Context context) {
        // for now, there is only one Whisper connection. Feature ID xxxxx captures
        // requirements for daisy chaining
        // whisper devices, in which case, we need to modify this code to get all devices
        // for now just create a default
        try {
            ClassLoader cl = context.getClassLoader();
            Class SystemProperties = cl.loadClass("android.os.SystemProperties");
            Class[] paramTypes= new Class[1];
            paramTypes[0]= String.class;
            Method get = SystemProperties.getMethod("get", paramTypes);
            //Parameters
            Object[] params= new Object[1];
            params[0]= new String("hw.whisper");
            String s= (String) get.invoke(SystemProperties, params);
            if ( s.length() > 0 ) {
               String[] ret = new String[]{s};
               return ret;
            }
        }catch( IllegalArgumentException iAE ){
            // TODO
        }catch( Exception e ){
            // TODO
        }
        return null;
    }
    // implementation, API needs to be exposed
    public static int getSemuID(String accessory_id) {
        String[] parts = accessory_id.split(",");
        if ( parts.length !=2 ) {
            // return a bad id?
            return CLASS_TYPE_INVALID;
        }
        try {
            int semuid = Integer.parseInt(parts[1],16);
            return semuid;
        }
        catch (NumberFormatException e) {
            // TODO
        }
        return CLASS_TYPE_INVALID;
    }
    // implementation, API needs to be exposed
    public static int getClassType(String accessory_id) {
        return ( (getSemuID(accessory_id)>>19) & 0x0F );
    }
}
